package com.tq68.weixin.utils;

import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Date;

import org.apache.commons.codec.binary.Base64;

import com.jfinal.kit.PathKit;
import com.tq68.weixin.common.WeixinConfig;

public class Base64ForFile {

	public static String GenerateImage(String base64Img){
        if (base64Img == null){
        	return "";
        }
        base64Img = base64Img.substring(base64Img.indexOf("base64,")+"base64,".length());
        Base64 base64 = new Base64();
        String fileName = "";
        String pathName = "";
        byte[] b = base64.decodeBase64(new String(base64Img).getBytes());
        try{
        	String ts = String.valueOf(new Date().getTime());
        	//新生成的图片，以当前时间命名
        	if(WeixinConfig.uploadpath.startsWith("/")){
        		pathName = WeixinConfig.uploadpath+"/" + ts + ".jpg";
        	}else{
        		pathName = PathKit.getWebRootPath() + "/" +WeixinConfig.uploadpath+"/" + ts + ".jpg";
        	}
        	fileName = ts + ".jpg";
        	//生成jpeg图片
            OutputStream out = new FileOutputStream(pathName);    
            out.write(b);
            out.flush();
            out.close();
            return fileName;
        }catch (Exception e){
            e.printStackTrace();
        	return "";
        }
	}
	
	public static String base64Image(String filePath){
		String base64Img = "";
		if(filePath != null){
			return base64Img;
		}
		
		return base64Img;
	}
}
